package co.example.michael.application;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;
import android.util.LruCache;

import java.io.File;

import libcore.io.DiskLruCache;

/**
 * Created by Michael on 2015/3/20.
 */
public class CustomApplication extends Application {

    //图片的缓存区
    public static LruCache<String, Bitmap> lruCache;

    //sd卡图片缓存区
    public static DiskLruCache diskLruCache;

    //sd卡缓存文件的名字
    private final String DISK_NAME = "Picbitmap";

    //sd卡缓存区的大小
    private final int DISK_SIZE = 10 * 1024 *1024;

    private final String TAG = "CustomApplication";

    //当前界面的context
    public static Context context;

    @Override
    public void onCreate() {
        super.onCreate();

        context = getApplicationContext();

        //得到可用的最大的缓存区的大小
        int cacheSize = (int) Runtime.getRuntime().maxMemory();

        //图片缓存区的大小是cacheSize的1/8;
        int size = cacheSize / 8;
        //创建图片缓存的对象lruCache
        lruCache = new LruCache<String, Bitmap>(size) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };

        try{
            File diskFile = getDiskCacheFile(context,DISK_NAME);
            if (!diskFile.exists()){

                //新建一个文件
                diskFile.mkdirs();
            }

            //sd卡图片的缓存对象
            diskLruCache = DiskLruCache.open(diskFile,getAppVersion(context),1,DISK_SIZE);
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    /**
     * 得到sd卡缓存图片的文件File
     *
     * @param context
     * @param uniqueName
     * @return
     */
    private File getDiskCacheFile(Context context, String uniqueName) {

        String cachePath = "";

        //如果sd卡存在或者不可被移除的时候
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {

            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        Log.e(TAG, "cachePath=" + cachePath);
        Log.e(TAG, "sd卡图片缓存路径：" + cachePath + File.separator + uniqueName);
        return new File(cachePath + File.separator + uniqueName);
    }

    /**
     * 得到当前应用程序的版本号
     * @param context
     * @return
     */
    private int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }
}
